<template>
    <div class="login-wrap">
        <div class="login">
            <div v-if="!ishengping" style="height:100vh;overflow-y:hidden" class="mains">
                <el-button type="primary" round style="position:fixed;top:10px;right:10px;" @click="toindex" plain
                           size="small">返回主页
                </el-button>
                <!-- <img :src="require('@/assets/images/logo.png')" style="width:100px;position:absolute;top:40px;left:50%;margin-left:-50px" alt=""> -->
                <div style="">
                    <p class="title" style="margin-top:40px;color:#fff;font-size:1.6rem">用户登录</p>
                    <el-form label-position="left" label-width="80px" :model="form"
                             style="width:340px;position:relative;left:50%;margin-left:-170px;"
                             require-asterisk-position="left"
                             :rules="baseRules" ref="baseForm">
                        <el-form-item label="账户" prop="username" class="item">
                            <el-input v-model="form.username" placeholder="请输入用户名"/>
                        </el-form-item>
                        <el-form-item label="输入密码" prop="password" class="item">
                            <el-input v-model="form.password" show-password type="password" placeholder="请输入密码"/>
                        </el-form-item>
                    </el-form>
                    <el-button type="primary" @click="confirmOperation" style="width: 120px;" plain>登录</el-button>
                    <el-button type="primary" @click="toregister" style="width: 120px;" plain>注册</el-button>
                    <p class="findpwd" @click="tofindpwd">忘记密码，去重置</p>
                </div>

            </div>
            <div v-if="ishengping" class="main">
                <div style="position:fixed;width:100%;height:14vh;top:10vh;cursor: pointer;" @click="toindex"></div>
                <div class="card" :style="{
                // boxShadow: 'var(--el-box-shadow)',
            }">
                    <div class="title-wrap">
                        <img src="@/assets/images/login-logo.png" width="58"/>
                        <p class="title">实训设施智能管控平台</p>
                    </div>
                    <el-form label-position="right" label-width="100px" :model="form" class="login-form"
                             require-asterisk-position="left" :rules="baseRules" ref="baseForm">
                        <el-input class="ipt" v-model="form.username" placeholder="请输入用户名">
                            <template #prepend>
                                <el-icon color="#EEF3F9" size="20">
                                    <User/>
                                </el-icon>
                            </template>
                        </el-input>
                        <el-input class="ipt pwd" v-model="form.password" show-password type="password"
                                  placeholder="请输入用户密码">
                            <template #prepend>
                                <el-icon color="#EEF3F9" size="20">
                                    <Lock/>
                                </el-icon>
                            </template>
                        </el-input>

                        <div class="tip">
                            <el-checkbox v-model="checked" class="rememberMe">记住账号</el-checkbox>
                            <el-button type="text" @click="this.showForget = true" class="forgetPw">修改密码</el-button>
                        </div>
                        <div @click="confirmOperation" class="btn">登录</div>
                    </el-form>
                </div>
            </div>
        </div>
        <el-dialog
            v-model="showForget"
            title="修改密码"
            width="600px"
            :close-on-click-modal="false"
            align-center>
            <el-form :model="forgetForm" rules="forgetRule" label-width="auto" class="forgetWrap">
                <el-form-item label="账号" prop="userName">
                    <el-input v-model="forgetForm.userName" clearable placeholder="请输入账号"/>
                </el-form-item>
                <el-form-item label="旧密码" prop="password">
                    <el-input v-model="forgetForm.password" clearable type="password" placeholder="请输入旧密码"/>
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                    <el-input v-model="forgetForm.newPassword" clearable type="password" placeholder="请输入新密码"/>
                </el-form-item>
                <el-form-item label="确认新密码" prop="newPasswordAgain">
                    <el-input v-model="forgetForm.newPasswordAgain" clearable type="password"
                              placeholder="请确认新密码"/>
                </el-form-item>

                <div class="tips">*密码长度8-18位且必须包含大写字母、小写字母、数字、符号中的三种。</div>

                <el-form-item>
                    <div class="btns">

                        <el-button @click="this.showForget=false">取消</el-button>
                        <el-button type="primary" @click="forgetPw">确定</el-button>
                    </div>
                </el-form-item>
            </el-form>

        </el-dialog>
    </div>
</template>
<script>
import {ElMessage, ElMessageBox} from 'element-plus'
import {ElNotification} from 'element-plus'
import wx from 'weixin-js-sdk'
let emailRegExp=/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
let reg_tel_phone = /(^((\+86)|(86))?(1[3-9])\d{9}$)|(^(0\d{2,3})-?(\d{7,8})$)/
export default {
    data() {
        return {
            forgetForm: {
                userName: '',
                password: '',
                newPassword: '',
                newPasswordAgain: '',
            },
            forgetRule: {
                userName: [{required: true, message: '账号为必填项', trigger: 'blur'}],
                password: [{required: true, message: '旧密码为必填项', trigger: 'blur'}],
                newPassword: [{required: true, message: '新密码为必填项', trigger: 'blur'}],
                newPasswordAgain: [{required: true, message: '确认新密码为必填项', trigger: 'blur'}],

            },
            ishengping: true,
            islogin: false,
            baseRules: {
                username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
                password: [{required: true, message: '请输入密码', trigger: 'blur'}],
            },
            form: {
                username: '',
                password: '',
            },
            ContainerStyle: {
                position: "fixed",
                left: "50%",
                top: "50%",
                "transform-origin": "0 0",
                transform: "scaleX(0.7) scaleY(0.7) translate(-50%, -50%)"
            },
            styleType: 3,
            userInfo: {
                userId: 0,
                username: '',
                role: ''
            },
            checked: false,
            showForget: false,
        }
    },
    methods: {
        forgetPw() {
            // 忘记密码
            this.axios.post(`http://20.19.195.3:9004/user/updatePassword`, {
                userName: this.forgetForm.userName,
                password: this.forgetForm.password,
                newPassword: this.forgetForm.newPassword,
                newPasswordAgain: this.forgetForm.newPasswordAgain,
            }).then((res) => {
                if (res.data.code == 200) {
                    this.showForget = false
                    this.forgetForm = {
                        userName: '',
                        password: '',
                        newPassword: '',
                        newPasswordAgain: '',
                    }
                    ElMessageBox.alert(`修改成功`, '消息', {
                        confirmButtonText: '知道了',
                    })
                } else {
                    ElMessageBox.alert(`⚠️ ${res.data.message}`, '消息', {
                        confirmButtonText: '知道了',
                    })
                }
            })
        },
        resize() {
            let width = window.innerWidth,
                height = window.innerHeight,
                $wrapper = document.getElementById("app"),
                style = "";
            // if (width >= height) { // 横屏
            //     this.ishengping = true
            //     // const w = window.innerWidth / 1920
            //     // const h = window.innerHeight / 1080
            //     // console.log(w, h)
            //     // switch(this.styleType){
            //     //     // 宽和高同时缩放
            //     //     case 1: this.ContainerStyle.transform = `scaleX(${w}) scaleY(${h}) translate(-50%, -50%)`; break;
            //     //     // 以宽度比例等比缩放
            //     //     case 2: this.ContainerStyle.transform = `scale(${w}) translate(-50%, -50%)`; break;
            //     //     // 以高度比例等比缩放
            //     //     case 3: this.ContainerStyle.transform = `scale(${h}) translate(-50%, -50%)`; break;
            //     // }
            // }else{
            //     this.ishengping = false
            // }
        },
        toindex() {
            let self = this
            this.$router.beforeEach((to, from, next) => {
                const isLoggedIn = window.localStorage.getItem('token')// 检查用户是否已经登录
                const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
                const roles = to.meta.roles || [];
                let role = window.localStorage.getItem('role')
                if (role == '管理员') {
                    role = 'admin'
                }
                if (requiresAuth && !isLoggedIn) {
                    // 如果需要登录且用户未登录，则跳转到登录页
                    next('/login');
                } else if (requiresAuth && roles.length > 0 && role == '') {
                    // 如果需要登录且需要角色权限且用户不具备对应的角色权限，则跳转到无权限提示页
                    next('/forbidden');
                } else {
                    // 其他情况均放行
                    next();
                }
            })
            this.$router.push({name:'index'})
        },
        toregister() {
            this.$router.push({name: 'register'})
        },
        tofindpwd() {
            this.$router.push({name: 'findpwd'})
        },
        confirmOperation() {
            let self = this
            this.$refs.baseForm.validate((valid) => {
                if (!valid) {
                    ElMessageBox.alert('⚠️ 请根据提示输入信息', '消息', {
                        confirmButtonText: '知道了',
                    })
                    return false
                } else {
                    self.login()
                }
            })
        },
        login() {
            let self = this
            let sendData = {
                userName: this.form.username,
                password: this.form.password
            }
            if (this.checked) {
                localStorage.setItem("loginUsername", this.form.username);
            } else {
                localStorage.removeItem("loginUsername");
            }

            this.axios.post('http://20.19.195.3:9004/h5/login', sendData).then((res) => {
                console.log(res)
                if (res.data.code == 200) {
                    localStorage.setItem('userId', res.data.data.userId)
                    // if(res.data.data.role_permission == '管理员'){
                        localStorage.setItem('role', res.data.data.role_permission)
                    // }
                    localStorage.setItem('token', res.data.data.token)
                    localStorage.setItem('username', self.form.username) // 登录的时间
                    self.toindex()
                } else {
                    ElMessageBox.alert(`⚠️ ${res.data.message}`, '消息', {
                        confirmButtonText: '知道了',
                    })
                }
            }).catch((err) => {
                ElMessageBox.alert(`⚠️ ${err}，请检查网络设置`, '消息', {
                    confirmButtonText: '知道了',
                })
            })
        }
    },
    mounted() {

        let username = localStorage.getItem("loginUsername");
        if (username) {
            this.form.username = username;
            this.checked = true;
        }

        let viewport = window.document.getElementById("viewport")
        viewport.content = "width=device-width,initial-scale=1.0,height=device-height,initial-scale=1.0"
        this.axios.get(`http://121.196.189.30:8848/getSignature?path=graph`, {
        }).then((res) => {
            this.nonceStr = res.data.nonceStr
            this.signature = res.data.signature
            this.timestamp = res.data.timestamp
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: 'wx9ba52b5d97f1f9af', // 必填，公众号的唯一标识
                timestamp: this.timestamp, // 必填，生成签名的时间戳
                nonceStr: this.nonceStr, // 必填，生成签名的随机串
                signature: this.signature,// 必填，签名
                jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'] // 必填，需要使用的JS接口列表
            })
            wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
                wx.updateAppMessageShareData({
                    title: `智慧电网与时序图计算科研云，助力智慧物联新工科及生态体系建设！`, // 分享标题
                    desc: '打造网络化、数字化、移动化、智能化的在线"教学+实验+科研+培训+大赛”全栈式综合服务平台。', // 分享描述
                    link: `http://www.aiotslab.com/graph/#/login`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: `http://121.196.189.30:7777/img/1731504100408954880.jpg`, // 分享图标
                    success: function () {
                        // 设置成功
                    }
                })
                wx.updateTimelineShareData({
                    title: `智慧电网与时序图计算科研云，助力智慧物联新工科及生态体系建设！`, // 分享标题
                    desc: '打造网络化、数字化、移动化、智能化的在线"教学+实验+科研+培训+大赛”全栈式综合服务平台。', // 分享描述
                    link: `http://www.aiotslab.com/graph/#/login`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: `http://121.196.189.30:7777/img/1731504100408954880.jpg`, // 分享图标
                    success: function () {
                        // 设置成功
                    }
                })
            })
        })
        window.addEventListener('resize', this.resize)
        this.resize()
    },
    watch: {
        $route() {
            // location.reload()
        },
    },
    // computed: {
    //     ...mapGetters(['isAuthenticated', 'getUser']),
    // }
}
</script>

<style scoped>
.item .el-form-item__label {
    color: #fff
}

.el-radio__label {
    color: #fff;
}

.main {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0px;
    left: 0px;
    background: url('../assets/images/login-bg.png');
    background-size: cover;
}

.mains {
    width: 100%;
    height: 100%;
    /* background: url('../assets/images/loginbg2.jpg');
    background-size: 100% 100% */
}

:deep(.el-input-group__prepend) {
    background-color: #67757E4D;
    box-shadow: none;
    padding: 0 10px;
}

:deep(.el-input__wrapper) {
    background-color: #67757E4D;
    box-shadow: none;

}

:deep(.el-input__inner) {
    color: #EEF3F9;
}

:deep(.el-input-group--prepend) {
    border: 1px solid;
    border-image: linear-gradient(to right, rgba(203, 227, 255, 0.75), rgba(203, 227, 255, 0)) 1;
}

.forgetWrap {
    padding: 0 12px;

    .tips {
        text-align: left;
    }

    .btns {
        width: 100%;
        padding-top: 20px;
        display: flex;
        justify-content: flex-end;
    }
}

:deep(.forgetWrap .el-input__inner) {
    background-color: white;
    color: black;
}

:deep(.forgetWrap .el-input__wrapper) {
    background-color: white;
    outline: 1px solid lightgray;
}

.card {
    width: 440px;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(50%, -50%);

    .title-wrap {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 105px;
        line-height: 105px;
        margin-bottom: 4px;
        background: rgba(45, 46, 46, 0.7);
        border: 1px solid;
        border-image: linear-gradient(to right, rgba(203, 227, 255, 0.75), rgba(203, 227, 255, 0)) 1;

        .title {
            font-size: 30px;
            color: #fff;
            text-align: center;
            font-weight: 400;
            margin-left: 10px;
            font-family: 'YouSheBiaoTiHei';
        }
    }

    .login-form {
        padding: 40px;
        background: rgba(45, 46, 46, 0.7);
        border: 1px solid;
        border-image: linear-gradient(to right, rgba(203, 227, 255, 0.75), rgba(203, 227, 255, 0)) 1;

        .ipt {
            height: 44px;
            line-height: 44px;
            background-color: #67757E4D;

            &.pwd {
                margin-top: 20px;
            }
        }

        .tip {
            display: flex;
            justify-content: space-between;
            margin-top: 20px;
        }

        .type {
            margin: 20px;
        }

        .btn {

            border: 1px solid;
            border-image: linear-gradient(to right, rgba(203, 227, 255, 0.75), rgba(203, 227, 255, 0)) 1;
            height: 44px;
            line-height: 44px;
            color: #fff;
            font-size: 16px;
            cursor: pointer;
            background: rgba(45, 46, 46, 0.7);
        }
    }
}

.sendyz {
    color: #409eff;
    cursor: pointer;
    display: inline;
}

.tologin {
    color: #409eff;
    cursor: pointer;
    margin-top: 6px;
    display: inline-block;
    margin-left: 50px
}

.tologin2 {
    color: #409eff;
    cursor: pointer;
    margin-top: 6px;
    display: inline-block;
    margin-right: 50px
}

.findpwd {
    color: #fff;
    cursor: pointer;
    width: 100%;
    margin-top: 10px;
    background: none
}
</style>